# -*- coding:utf-8 -*-
#测试pr
import pygame
import sys
import random

import time

# 全局定义
SCREEN_X = 600
SCREEN_Y = 600


# 蛇类
# 点以25为单位
class Snake(object):
    # 初始化各种需要的属性 [开始时默认向右/身体块x5]
    def __init__(self,chushix = 0,chushiy = 0):
        self.dirction = pygame.K_RIGHT
        self.body = []
        for x in range(5):
            self.addnode(chushix,chushiy)

    # 无论何时 都在前端增加蛇块
    def addnode(self,chsx = 0,chsy = 0):
        left, top = (chsx, chsy)
        if self.body:
            left, top = (self.body[0].left, self.body[0].top)
        node = pygame.Rect(left, top, 25, 25)
        if self.dirction == pygame.K_LEFT or self.dirction == pygame.K_a:
            node.left -= 25
        elif self.dirction == pygame.K_RIGHT or self.dirction == pygame.K_d:
            node.left += 25
        elif self.dirction == pygame.K_UP or self.dirction == pygame.K_w:
            node.top -= 25
        elif self.dirction == pygame.K_DOWN or self.dirction == pygame.K_s:
            node.top += 25
        self.body.insert(0, node)

    # 删除最后一个块
    def delnode(self):
        self.body.pop()


    # 自断一逼
    def iscatme(self):
        if self.body[0] in self.body[1:]:
            p=self.body[1:].index(self.body[0])
            print(p)
            del self.body[p:]

    # 死亡判断
    def isdead(self,food):
        # 撞墙
        if self.body[0].x not in range(SCREEN_X):
            return True,[]
        if self.body[0].y not in range(SCREEN_Y):
            return True,[]
        # 撞自己
        if self.body[0] in self.body[1:]:
            #print(" --------------------  ")
            a = self.body.index(self.body[0],1)
            food.extend(self.body[a+1:])
            del self.body[a:]
        return False,food

    # 移动！
    def move(self):
        self.addnode()
        self.delnode()

    # 改变方向 但是左右、上下不能被逆向改变
    def changedirection(self, curkey,zy):
        if zy == 1:
            LR = [pygame.K_LEFT, pygame.K_RIGHT]
            UD = [pygame.K_UP, pygame.K_DOWN]
        else:
            LR = [pygame.K_a, pygame.K_d]
            UD = [pygame.K_w, pygame.K_s]
        if curkey in LR + UD:
            if (curkey in LR) and (self.dirction in LR):
                return
            if (curkey in UD) and (self.dirction in UD):
                return
            self.dirction = curkey


# 食物类
# 方法： 放置/移除
# 点以25为单位
class Food:
    def __init__(self):
        self.rect = pygame.Rect(-25, 0, 25, 25)
        self.snakefood = []

    def remove(self):
        self.rect.x = -25

    def set(self,snake01,snake02):
        if self.rect.x == -25:
            allpos = []
            # 不靠墙太近 25 ~ SCREEN_X-25 之间
            for pos in range(25, SCREEN_X - 25, 25):
                allpos.append(pos)
            self.rect.left = random.choice(allpos)
            self.rect.top = random.choice(allpos)
            if self.rect in self.snakefood:
                self.rect.x = -25
                self.set(snake01,snake02)
            if self.rect in snake02:
                self.rect.x = -25
                self.set(snake01,snake02)
            if self.rect in snake01:
                self.rect.x = -25
                self.set(snake01,snake02)
            return

            #print(self.rect)


def show_text(screen, pos, text, color, font_bold = False, font_size = 60, font_italic = False):
    #获取系统字体，并设置文字大小
    cur_font = pygame.font.SysFont("simHei", font_size)
    #设置是否加粗属性
    cur_font.set_bold(font_bold)
    #设置是否斜体属性
    cur_font.set_italic(font_italic)
    #设置文字内容
    text_fmt = cur_font.render(text, 1, color)
    #绘制文字
    screen.blit(text_fmt, pos)


def main():
    pygame.init()
    screen_size = (SCREEN_X, SCREEN_Y)
    screen = pygame.display.set_mode(screen_size)
    pygame.display.set_caption('Snake')
    clock = pygame.time.Clock()
    scores = 0
    isdead = False

    # 蛇/食物
    snake1 = Snake(0,0)
    snake2 = Snake(0,100)
    food = Food()
    jg = 3

    # time.sleep(9000)

    jieshu = False

    isdead1 = False
    isdead2 = False
    while True:
        for event in pygame.event.get():
            print("anjian")
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == pygame.KEYDOWN:
                #print(event.key)
                snake1.changedirection(event.key,2)
                snake2.changedirection(event.key,1)
                # 死后按space重新
                if event.key == pygame.K_SPACE and jieshu:
                    jieshu = False
                    print("重启游戏")
                    return main()

        if jieshu:
            clock.tick(jg)
            continue


        screen.fill((255, 255, 255)) # 背景
        #
        # 画蛇身 / 每一步+1分 self.snakefood
        # 食物处理 / 吃到+50分

        if food.rect == snake1.body[0]:
            scores+=1
            food.remove()
            snake1.addnode()
        elif snake1.body[0] in food.snakefood:# 吃自己
            scores+=1
            food.snakefood.remove(snake1.body[0])
            snake1.addnode()
        else:
            snake1.move()

        if food.rect == snake2.body[0]:
            scores+=1
            food.remove()
            snake2.addnode()
        elif snake2.body[0] in food.snakefood:# 吃自己
            scores+=1
            food.snakefood.remove(snake2.body[0])
            print("jia")
            snake2.addnode()
        else:
            snake2.move()

        # 显示死亡文字

        #print("food",food.snakefood)
        isdead1, food.snakefood = snake1.isdead(food.snakefood)  # 自己咬断自己
        isdead2, food.snakefood = snake2.isdead(food.snakefood)  # 自己咬断自己
        #print("food",food.snakefood)
        if isdead1 or isdead2 or snake2.body[0] in snake1.body[0:-1] or snake1.body[0] in snake2.body[0:-1]:
            jieshu = True
            if len(snake1.body) > len(snake2.body):
                show_text(screen, (50, 100), '一号玩家胜利!', (150, 29, 18), False, 50)
            elif len(snake1.body) == len(snake2.body):
                show_text(screen, (50, 100), '平局!', (150, 29, 18), False, 50)
            else:
                show_text(screen, (50, 100), '二号玩家胜利!', (150, 29, 18), False, 80)
            show_text(screen, (100, 200), '游戏结束!', (227, 29, 18), False, 100)
            show_text(screen, (150, 360), 'press space to try again...', (0, 0, 22), False, 30)
        elif snake2.body[0] == snake1.body[-1]:
            snake2.addnode()
            snake1.body.pop()
        elif snake1.body[0] == snake2.body[-1]:
            snake1.addnode()
            snake2.body.pop()
        # 食物投递
        food.set(snake1.body,snake2.body)

        pygame.draw.rect(screen, (136, 0, 21), food.rect, 0)

        pygame.draw.rect(screen, (200, 160, 39), snake1.body[0], 0)
        for rect in snake1.body[1:]:
            pygame.draw.rect(screen, (20, 80, 39), rect, 0)
        pygame.draw.rect(screen, (200, 0, 0), snake2.body[0], 0)
        for rect in snake2.body[1:]:
            pygame.draw.rect(screen, (20, 220, 39), rect, 0)

        for stFood in food.snakefood:
            pygame.draw.rect(screen, (100, 20, 150), stFood, 0)
        # snake.iscatme() # # 自断一逼

        pygame.display.update()
        clock.tick(jg)

if __name__ == '__main__':
    main()


